<template>
	<div class="dgtPage">
		<div class="jsjf">
			<img src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/shijian.png" alt="" />
			<span class="text">{{ formattedTime }}</span>
			<img src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/jifen.png" alt="" />
			<span class="text">{{ state.jifen }}</span>
		</div>
		<div class="xiachusnsadja">点击相邻两个交换位置<br/>三个相同即可消除成功<br/>消除十组即可通关</div>
		<div class="playBox" v-if="state.boxShow">
			<div class="rowBox" v-for="(itemRow, indexRow) of state.boxList" :key="indexRow">
				<div
					v-for="(itemCol, indexCol) of itemRow"
					:key="indexCol"
					:class="[
						noBox(indexRow, indexCol) ? (itemCol.is ? 'colBox' : 'noColBox') : 'noColBox',
						`colBox_${indexRow}_${indexCol}`,
						actionState(indexRow, indexCol) ? 'colBox_action' : '',
					]"
					@click="selectBox(indexRow, indexCol)"
				>
					<img v-if="itemCol.noShow && itemCol.is" style="height: 30px" :src="itemCol.img" alt="" />
				</div>
			</div>
		</div>
		<div class="caidanBtn" @click="state.tcShow = true">
			<img src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/caidan.png" alt="" />
		</div>
		<div class="tanchuang" v-if="state.tcShow">
			<div class="neirong">
				<div class="topBox" v-if="state.jifen < 1600">
					<img class="weitonghuan" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/weitonghuan.png" alt="" />
				</div>
				<img class="gb" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image/gb.png" alt="" @click="state.tcShow = false" />
				<div class="btnList">
					<img src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/cxks.png" alt="" @click="chongzhi" />
					<img v-if="state.jifen > 1600" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/tcyx.png" alt="" @click="router.push({ path: '/playIndex' })" />
					<img v-if="state.jifen < 1600 && !state.userQtShow" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/tiaoguo.png" alt="" @click="goDati" />
				</div>
				<img class="xfy" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/xfy.png" alt="" />
				<img class="yf" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image2/yf1.png" alt="" />
				<img class="xj" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image/xiangji.png" alt="" />
			</div>
		</div>
		<div class="tanchuangGG" v-if="state.guoguan">
			<div class="neirong">
				<div class="topBox">
					<img class="weitonghuan" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/gxtg.png" alt="" />
				</div>
				<img class="xcjf" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/xcjf.png" alt="" />
				<img class="gb" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image/gb.png" alt="" @click="state.guoguan = false" />
				<div class="btnList">
					<img style="width: 90%" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/ggIcon.png" alt="" />
					<img v-if="!state.userQtShow" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/jrxyg.png" alt="" @click="router.push({ path: '/answer' })" />
					<img v-else src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/fhsy.png" alt="" @click="router.push({ path: '/home' })" />
				</div>
				<img class="xfy" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/xfy.png" alt="" />
				<img class="yf" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image2/yf1.png" alt="" />
				<img class="xj" src="https://vivo.zhongwangyingtong.com/vivoimage/assets/image/xiangji.png" alt="" />
			</div>
		</div>
	</div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, nextTick, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { gsap } from 'gsap';
import { Session } from '../../utils/storage';
// import mj from 'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/mujing.png';
// import hg from 'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hg.png';
// import xj from 'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/xj.png';
// import hlh from 'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hlh.png';
// import hz from 'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hz.png';
import { ElMessage } from 'element-plus';

const router = useRouter();
const state = reactive({
	boxList: [],
	actionList: [],
	findMatchingNodesList: [],
	jifen: 0,
	tcShow: false,
	guoguan: false,
	userQtShow: false,
	kaishiyouxi: false,
	boxShow: false,
  itemImages:[
    'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/mujing.png',
    'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hg.png',
    'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/xj.png',
    'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hlh.png',
    'https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/hz.png'
  ]
});
const goDati = () => {
	router.push({
		path: '/answer',
	});
};
const timeLeft = ref(120);
// 格式化时间显示
const formattedTime = computed(() => {
	const minutes = Math.floor(timeLeft.value / 60);
	const seconds = timeLeft.value % 60;
	return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
});
// 倒计时逻辑（使用箭头函数）
let interval;
const startCountdown = () => {
	interval = setInterval(() => {
		if (timeLeft.value > 0) {
			timeLeft.value--;
		} else {
			// clearInterval(interval);
			if (state.jifen < 1600) {
				console.log('失败');
				state.tcShow = true;
				// chongzhi()
			}
		}
	}, 1000);
};
//不需要展示的模块
const noBox = (index: any, item: any) => {
	if (
		(index === 0 && item === 0) ||
		(index === 0 && item === 1) ||
		(index === 0 && item === 5) ||
		(index === 0 && item === 6) ||
		(index === 1 && item === 0) ||
		(index === 1 && item === 6) ||
		(index === 5 && item === 0) ||
		(index === 5 && item === 3) ||
		(index === 5 && item === 6)
	) {
		return false;
	} else {
		return true;
	}
};
//自动生成
const randomGeneration = () => {
	const images = state.itemImages;
	let maxEliminations = 0; // 设置最大允许的消除数量为0
	let attempts = 0;
	let validGrid = false;

	while (!validGrid && attempts < 100) {
		// 最多尝试100次，避免无限循环
		state.boxList = []; // 清空当前的方块列表
		for (let index = 0; index < 6; index++) {
			let rowList = [];
			for (let item = 0; item < 7; item++) {
				const randomIndex = Math.floor(Math.random() * images.length);
				const randomImage = images[randomIndex];
				rowList.push({
					id: `colBox_${index}_${item}`,
					action: false,
					index: index,
					item: item,
					img: randomImage,
					type: noBox(index, item) ? randomIndex : -1,
					noShow: noBox(index, item),
					is: true,
				});
			}
			state.boxList.push(rowList);
		}

		// 检查生成的方块是否有消除
		const eliminations = findMatchingNodes(state.boxList).length;
		if (eliminations <= maxEliminations) {
			validGrid = true; // 如果消除数量在允许范围内，退出循环
		} else {
			attempts++; // 否则继续尝试生成新的方块
		}
	}

	if (validGrid) {
		state.boxShow = true;
	} else {
		// 如果尝试了100次仍然没有生成合适的方块，可以采取其他措施，比如减少消除数量或提示用户
		console.error('无法生成合适的方块布局');
		state.boxShow = false;
	}
};
//计算是否点击
const actionState = (index: any, item: any) => {
	let stateItem = false;
	if (state.boxList.length) {
		if (state.boxList[index][item].action) {
			stateItem = true;
		} else {
			stateItem = false;
		}
	}
	return stateItem;
};
//点击动画
const gsapQuiver = (index: any, item: any) => {
	const gsapQuiverTl = gsap.timeline();
	gsapQuiverTl
		.to(`.colBox_${index}_${item}`, {
			duration: 0.05,
			rotation: -5,
		})
		.to(`.colBox_${index}_${item}`, {
			duration: 0.05,
			rotation: 10,
		})
		.to(`.colBox_${index}_${item}`, {
			duration: 0.05,
			rotation: 0,
		});
};
//点击选中
const selectBox = (index: any, item: any) => {
	if (noBox(index, item)) {
		gsapQuiver(index, item);
		state.actionList.push({ index: index, item: item });
		state.boxList[index][item].action = true;
		if (state.actionList.length >= 2) {
			isAdjoin();
		}
	} else {
		console.log('你点了不该点的位置');
	}
};
//取消两个块的选中状态
const cancelBoxAc = () => {
	setTimeout(() => {
		for (let index of state.boxList) {
			for (let itemCol of index) {
				itemCol.action = false;
			}
		}
		state.actionList = [];
	}, 500);
};
//交换两个块的位置
const interchangeBox = (type: any) => {
	const yidong = gsap.timeline();
	state.kaishiyouxi = true;

	// 边界检查函数
	const isValidIndex = (index: number, item: number) => {
		return index >= 0 && index < state.boxList.length && item >= 0 && item < state.boxList[index].length;
	};

	// 检查 actionList 是否有效
	if (!state.actionList[0] || !state.actionList[1]) {
		console.error('Action list items are undefined');
		return;
	}

	// 复制 actionList 以避免异步问题
	const actionListCopy = [...state.actionList];

	// 检查索引是否有效
	if (!isValidIndex(actionListCopy[0].index, actionListCopy[0].item) || !isValidIndex(actionListCopy[1].index, actionListCopy[1].item)) {
		console.error('Invalid index or item');
		return;
	}

	// 调试信息
	console.log('Action List:', actionListCopy);
	console.log('Box List:', state.boxList);

	if (type === '2') {
		const offset1 = 52 * (actionListCopy[1].item - actionListCopy[0].item);
		const offset2 = 52 * (actionListCopy[0].item - actionListCopy[1].item);

		yidong
			.to(`.colBox_${actionListCopy[0].index}_${actionListCopy[0].item}`, {
				duration: 0.5,
				x: offset1,
				onComplete: function () {
					gsap.set(this.targets(), { x: 0, clearProps: 'x' });
				},
			})
			.to(
				`.colBox_${actionListCopy[1].index}_${actionListCopy[1].item}`,
				{
					duration: 0.5,
					x: offset2,
					onComplete: function () {
						gsap.set(this.targets(), { x: 0, clearProps: 'x' });
						nextTick(() => {
							// 交换逻辑
							let zancun1 = state.boxList[actionListCopy[0].index][actionListCopy[0].item];
							let zancun2 = state.boxList[actionListCopy[1].index][actionListCopy[1].item];
							state.boxList[actionListCopy[0].index][actionListCopy[0].item] = zancun2;
							state.boxList[actionListCopy[1].index][actionListCopy[1].item] = zancun1;
							findMatchingNodes(state.boxList);
							// 如果没有匹配的节点，则恢复原状
							if (!state.findMatchingNodesList.length) {
								state.boxList[actionListCopy[0].index][actionListCopy[0].item] = zancun1;
								state.boxList[actionListCopy[1].index][actionListCopy[1].item] = zancun2;
							} else {
								for (let jiac of state.findMatchingNodesList) {
									console.log(state.findMatchingNodesList);
									console.log(111);
									eliminationOfContinuity();
								}
							}
						});
					},
				},
				'-=0.5'
			);
	}

	if (type === '1') {
		const offset1 = 52 * (actionListCopy[1].index - actionListCopy[0].index);
		const offset2 = 52 * (actionListCopy[0].index - actionListCopy[1].index);

		yidong
			.to(`.colBox_${actionListCopy[0].index}_${actionListCopy[0].item}`, {
				duration: 0.5,
				y: offset1,
				onComplete: function () {
					gsap.set(this.targets(), { y: 0, clearProps: 'y' });
				},
			})
			.to(
				`.colBox_${actionListCopy[1].index}_${actionListCopy[1].item}`,
				{
					duration: 0.5,
					y: offset2,
					onComplete: function () {
						gsap.set(this.targets(), { y: 0, clearProps: 'y' });
						nextTick(() => {
							// 交换逻辑
							let zancun1 = state.boxList[actionListCopy[0].index][actionListCopy[0].item];
							let zancun2 = state.boxList[actionListCopy[1].index][actionListCopy[1].item];
							state.boxList[actionListCopy[0].index][actionListCopy[0].item] = zancun2;
							state.boxList[actionListCopy[1].index][actionListCopy[1].item] = zancun1;
							findMatchingNodes(state.boxList, 0);
							// 如果没有匹配的节点，则恢复原状
							if (!state.findMatchingNodesList.length) {
								state.boxList[actionListCopy[0].index][actionListCopy[0].item] = zancun1;
								state.boxList[actionListCopy[1].index][actionListCopy[1].item] = zancun2;
							} else {
								for (let jiac of state.findMatchingNodesList) {
									console.log(state.findMatchingNodesList);
									console.log(111);
									eliminationOfContinuity();
								}
							}
						});
					},
				},
				'-=0.5'
			);
	}

	console.log('Final Action List:', state.actionList);
};
//坐标系函数
const areAdjacent = (x1: any, y1: any, x2: any, y2: any) => {
	if (Math.abs(x1 - x2) === 1 && y1 === y2) return { type: '2', bot: true };
	else if (Math.abs(y1 - y2) === 1 && x1 === x2) return { type: '1', bot: true };
	else return { type: '0', bot: false };
};
//判断是否相邻
const isAdjoin = () => {
	let colBox1 = state.actionList[0];
	let colBox2 = state.actionList[1];
	if (JSON.stringify(colBox1) !== JSON.stringify(colBox2)) {
		if (areAdjacent(colBox1.item, colBox1.index, colBox2.item, colBox2.index).bot) {
			interchangeBox(areAdjacent(colBox1.item, colBox1.index, colBox2.item, colBox2.index).type);
		} else {
			if(state.actionList.length > 2){
        state.actionList = []
        ElMessage.warning('请不要点击太快');
      } else {
        ElMessage.warning('请选择相邻的两个块');
      }

		}
		cancelBoxAc();
	} else {
		state.boxList[state.actionList[0].index][state.actionList[0].item].action = false;
	}
};
//判断消除算法
const findMatchingNodes = (data: any, typeNa: any = 1) => {
	const result = [];
	const checkHorizontal = (row: any, col: any) => {
		const type = data[row][col].type;
		if (type === -1) return false;

		let count = 1;

		for (let i = col + 1; i < data[row].length; i++) {
			if (data[row][i].type === -1) break;
			if (data[row][i].type === type) {
				count++;
			} else {
				break;
			}
		}

		for (let i = col - 1; i >= 0; i--) {
			if (data[row][i].type === -1) break;
			if (data[row][i].type === type) {
				count++;
			} else {
				break;
			}
		}

		return count >= 3;
	};

	const checkVertical = (row, col) => {
		const type = data[row][col].type;
		if (type === -1) return false;

		let count = 1;

		for (let i = row + 1; i < data.length; i++) {
			if (data[i][col].type === -1) break;
			if (data[i][col].type === type) {
				count++;
			} else {
				break;
			}
		}

		for (let i = row - 1; i >= 0; i--) {
			if (data[i][col].type === -1) break;
			if (data[i][col].type === type) {
				count++;
			} else {
				break;
			}
		}

		return count >= 3;
	};

	for (let row = 0; row < data.length; row++) {
		for (let col = 0; col < data[row].length; col++) {
			if (checkHorizontal(row, col) || checkVertical(row, col)) {
				result.push(data[row][col]);
			}
		}
	}
	state.findMatchingNodesList = result;
	if (state.kaishiyouxi) {
		state.jifen += state.findMatchingNodesList.length * 100;
	}

	if (state.jifen >= 1600) state.guoguan = true;
	console.log(state.findMatchingNodesList);
	return result;
};
//消除连续方块
const eliminationOfContinuity = () => {
	console.log('eliminationOfContinuity');
	const images = state.itemImages;
	if (state.findMatchingNodesList.length) {
		state.findMatchingNodesList.forEach((item: any) => {
			if (item.index === state.boxList[item.index][item.item].index && item.item === state.boxList[item.index][item.item].item) {
				nextTick(() => {
					gsap.timeline().to(`.colBox_${item.index}_${item.item}`, {
						duration: 0.5,
						opacity: 0,
						onComplete: function () {
							// state.boxList[item.index][item.item].is = false
							const randomIndex = Math.floor(Math.random() * images.length);
							state.boxList[item.index][item.item].img = images[randomIndex];
							state.boxList[item.index][item.item].type = randomIndex;
							gsap.set(this.targets(), { opacity: 1, clearProps: 'opacity' });
							findMatchingNodes(state.boxList);
						},
					});
				});
			}
		});
	}
};
//重置游戏
const chongzhi = () => {
	state.jifen = 0;
	state.actionList = [];
	state.boxList = [];
	state.findMatchingNodesList = [];
	clearInterval(interval);
	timeLeft.value = 120;
	randomGeneration();
	startCountdown();
	state.tcShow = false;
};
onMounted(() => {
	randomGeneration();
	startCountdown();
	if (Session.get('token') === '2') {
		state.userQtShow = true;
	}
});
onUnmounted(() => {
	clearInterval(interval);
});
</script>

<style scoped lang="scss">
.xiachusnsadja {
	position: absolute;
	top: 10%;
	z-index: 99999999;
	font-size: 18px;
	color: white;
}

.dgtPage {
	width: 100%;
	height: 100%;
	background: url('https://vivo.zhongwangyingtong.com/vivoimage/assets/image3/playBc.png');
	background-size: cover;
	background-position: center;
	background-repeat: no-repeat;
	position: relative;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;

	.jsjf {
		position: absolute;
		//width: 150px;
		//height: 35px;
		border-radius: 35px;
		background-color: white;
		top: 20px;
		left: 20px;
		padding: 4px 8px;
		display: flex;
		align-items: center;

		.text {
			margin: 0 8px 0 6px;
			color: #1a1a1a;
		}

		img {
			width: 25px;
		}
	}

	.playBox {
		.rowBox {
			display: flex;

			.colBox {
				width: 50px;
				height: 50px;
				background-color: #fef0ff;
				border: 1px solid black;
				border-radius: 8px;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
			}

			.colBox_action {
				width: 50px;
				height: 50px;
				background-color: #f694fd;
				border: 1px solid black;
				border-radius: 8px;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
			}

			.noColBox {
				width: 50px;
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				border: 1px solid rgba(0, 0, 0, 0);
			}
		}
	}

	.caidanBtn {
		margin-top: 40px;

		img {
			width: 55%;
		}
	}

	.tanchuang {
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: rgba(26, 26, 26, 0.45);
		display: flex;
		align-items: center;
		justify-content: center;

		.neirong {
			background-color: #fef0ff;
			border-radius: 24px;
			box-sizing: border-box;
			width: 85%;
			position: relative;

			.topBox {
				background-color: #bf78f7;
				width: 100%;
				height: 40px;
				border-top-left-radius: 24px;
				border-top-right-radius: 24px;
				display: flex;
				align-items: center;
				justify-content: center;

				.weitonghuan {
					height: 25px;
				}
			}

			.btnList {
				box-sizing: border-box;
				padding: 32px;
				display: flex;
				flex-direction: column;
				align-items: center;
				margin: 16px 0;

				img {
					width: 70%;
					margin-bottom: 30px;
				}
			}

			.xfy {
				position: absolute;
				bottom: -1px;
				left: 0;
				width: 100%;
			}

			.gb {
				position: absolute;
				width: 40px;
				right: -15px;
				top: -15px;
			}

			.yf {
				position: absolute;
				width: 70px;
				left: -10px;
				bottom: 40px;
			}

			.xj {
				width: 70px;
				position: absolute;
				right: -25px;
				top: 50px;
			}
		}
	}

	.tanchuangGG {
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: rgba(26, 26, 26, 0.45);
		display: flex;
		align-items: center;
		justify-content: center;

		.neirong {
			background-color: #fef0ff;
			border-radius: 24px;
			box-sizing: border-box;
			width: 85%;
			position: relative;

			.topBox {
				background-color: #bf78f7;
				width: 100%;
				height: 40px;
				border-top-left-radius: 24px;
				border-top-right-radius: 24px;
				display: flex;
				align-items: center;
				justify-content: center;

				.weitonghuan {
					height: 25px;
				}
			}

			.xcjf {
				height: 25px;
				position: absolute;
				left: 10px;
				top: 50px;
			}

			.btnList {
				box-sizing: border-box;
				padding: 32px;
				display: flex;
				flex-direction: column;
				align-items: center;
				margin: 16px 0;

				img {
					width: 60%;
					//margin-bottom: 30px;
				}
			}

			.xfy {
				position: absolute;
				bottom: -1px;
				left: 0;
				width: 100%;
			}

			.gb {
				position: absolute;
				width: 40px;
				right: -15px;
				top: -15px;
			}

			.yf {
				position: absolute;
				width: 70px;
				left: -10px;
				bottom: 40px;
			}

			.xj {
				width: 70px;
				position: absolute;
				right: -25px;
				top: 50px;
			}
		}
	}
}
</style>
